package com.kehao.leetcode.jzoffer;

import org.junit.Test;

import java.util.*;

public class JZSolution053 {

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        List<TreeNode> list = new ArrayList<>();
        dfs(root,p,list);
        return pos==-1||pos==list.size()?null:list.get(pos);
    }
    int pos = -1;
    private void dfs(TreeNode root, TreeNode p, List<TreeNode> list) {
        if(root==null) return;
        dfs(root.left,p, list);
        list.add(root);
        if(root==p){
            pos = list.size();
        }
        dfs(root.right,p,list);
    }

    @Test
    public void test01(){
        TreeNode treeNode = buildTree(new Integer[]{5,3,6,2,4,null,null,1});
        TreeNode resultNode = inorderSuccessor(treeNode, map.get(1));
        System.out.println(resultNode.val);
    }

    Map<Integer,TreeNode>  map = new HashMap<>();
    private TreeNode buildTree(Integer[] treeArray){
        TreeNode[] treeNodeList = new TreeNode[treeArray.length];
        for (int i = 0; i < treeArray.length; i++) {
            if(treeArray[i]!=null){
                treeNodeList[i] = new TreeNode(treeArray[i]);
                map.put(treeArray[i],treeNodeList[i]);
            }
        }
        for (int i = 0; i < treeNodeList.length/2; i++) {
            if(i*2+1<treeNodeList.length){
                treeNodeList[i].left = treeNodeList[i*2+1];
            }
            if(i*2+2<treeNodeList.length){
                treeNodeList[i].right = treeNodeList[i*2+2];
            }
        }
        return treeNodeList[0];
    }
}
